// 关键词高亮功能
class KeywordHighlighter {
  constructor() {
    this.settings = {
      enabled: true,
      scanDelay: 300,
      regexSupport: false,
      tooltipTheme: 'dark',
      tooltipPosition: 'follow'
    };
    this.groups = [];
    this.keywords = [];
    this.highlightedNodes = new Set();
    this.scanTimer = null;
    this.observer = null;
    this.tooltip = null;
    this.currentHighlight = null;
    this.isScrolling = false;
    this.scrollTimer = null;

    this.init();
  }

  // 初始化
  async init() {
    await this.loadData();
    this.createTooltip();
    this.setupScrollListener();
    this.setupMutationObserver();
    this.setupEventDelegation();
    this.startScan();

    // 监听来自popup的消息
    chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
      if (request.action === 'updateHighlight') {
        this.updateData(request);
        this.rehighlight();
      } else if (request.action === 'updateSettings') {
        this.settings = {...this.settings, ...request.settings};
        this.updateTooltipTheme(this.settings.tooltipTheme);
      }
    });
  }

  // 加载数据
  async loadData() {
    return new Promise(resolve => {
      chrome.storage.local.get(['groups', 'keywords', 'settings'], result => {
        if (result.groups) this.groups = result.groups;
        if (result.keywords) this.keywords = result.keywords;
        if (result.settings) this.settings = {...this.settings, ...result.settings};
        resolve();
      });
    });
  }

  // 更新数据
  updateData(data) {
    if (data.groups) this.groups = data.groups;
    if (data.keywords) this.keywords = data.keywords;
    if (data.settings) this.settings = {...this.settings, ...data.settings};
  }

  // 设置滚动监听
  setupScrollListener() {
    let scrollTimeout;
    window.addEventListener('scroll', () => {
      this.isScrolling = true;

      // 隐藏工具提示
      this.hideTooltip();

      // 清除之前的定时器
      clearTimeout(scrollTimeout);
      scrollTimeout = setTimeout(() => {
        this.isScrolling = false;
      }, 150);
    }, { passive: true });
  }

  // 设置MutationObserver监听DOM变化
  setupMutationObserver() {
    this.observer = new MutationObserver(mutations => {
      if (!this.settings.enabled) return;

      let shouldRescan = false;

      for (const mutation of mutations) {
        if (mutation.type === 'childList') {
          // 检查新增的节点是否包含文本
          for (const node of mutation.addedNodes) {
            if (node.nodeType === Node.TEXT_NODE ||
                (node.nodeType === Node.ELEMENT_NODE &&
                    this.containsText(node))) {
              shouldRescan = true;
              break;
            }
          }
        } else if (mutation.type === 'characterData') {
          // 文本内容变化
          shouldRescan = true;
        }

        if (shouldRescan) break;
      }

      if (shouldRescan) {
        clearTimeout(this.scanTimer);
        this.scanTimer = setTimeout(() => {
          this.scanDocument();
        }, this.settings.scanDelay);
      }
    });

    this.observer.observe(document.body, {
      childList: true,
      subtree: true,
      characterData: true
    });
  }

  // 检查元素是否包含文本
  containsText(element) {
    const walker = document.createTreeWalker(
        element,
        NodeFilter.SHOW_TEXT,
        null,
        false
    );

    let node;
    while (node = walker.nextNode()) {
      if (node.textContent.trim().length > 0) {
        return true;
      }
    }

    return false;
  }

  // 设置事件委托
  setupEventDelegation() {
    // 使用事件委托处理鼠标悬停事件
    document.addEventListener('mouseover', (e) => {
      if (this.isScrolling) return;

      const highlight = e.target.closest('.keyword-highlight');
      if (highlight) {
        this.showTooltip(e, highlight);
      }
    });

    document.addEventListener('mouseout', (e) => {
      if (e.target.classList.contains('keyword-highlight') ||
          e.relatedTarget?.classList.contains('keyword-highlight')) {
        this.hideTooltip();
      }
    });

    // 鼠标移动时更新工具提示位置
    document.addEventListener('mousemove', (e) => {
      if (this.tooltip && this.tooltip.style.opacity === '1' && this.currentHighlight) {
        this.positionTooltip(e);
      }
    });
  }

  // 创建工具提示元素
  createTooltip() {
    // 移除现有的工具提示
    const existingTooltip = document.getElementById('keyword-highlight-tooltip');
    if (existingTooltip) {
      existingTooltip.remove();
    }

    this.tooltip = document.createElement('div');
    this.tooltip.id = 'keyword-highlight-tooltip';
    this.tooltip.style.cssText = `
      position: fixed;
      z-index: 10000;
      pointer-events: none;
      opacity: 0;
      transition: opacity 0.15s ease;
      max-width: 300px;
      font-family: system-ui, -apple-system, sans-serif;
      font-size: 12px;
      line-height: 1.4;
      border-radius: 4px;
      padding: 6px 8px;
      box-shadow: 0 2px 8px rgba(0,0,0,0.3);
    `;

    this.updateTooltipTheme(this.settings.tooltipTheme);
    document.body.appendChild(this.tooltip);
  }

  // 更新工具提示主题
  updateTooltipTheme(theme) {
    if (!this.tooltip) return;

    if (theme === 'dark') {
      this.tooltip.style.background = '#333';
      this.tooltip.style.color = 'white';
    } else {
      this.tooltip.style.background = 'white';
      this.tooltip.style.color = '#333';
      this.tooltip.style.border = '1px solid #ddd';
    }
  }

  // 开始扫描文档
  startScan() {
    if (!this.settings.enabled) return;
    this.scanDocument();
  }

  // 扫描文档并高亮关键词
  scanDocument() {
    if (!this.settings.enabled || this.keywords.length === 0) {
      this.removeHighlights();
      return;
    }

    // 使用TreeWalker高效遍历文本节点
    const walker = document.createTreeWalker(
        document.body,
        NodeFilter.SHOW_TEXT,
        {
          acceptNode: node => {
            // 跳过脚本、样式等元素
            const parent = node.parentElement;
            if (!parent) return NodeFilter.FILTER_REJECT;

            if (parent.tagName === 'SCRIPT' ||
                parent.tagName === 'STYLE' ||
                parent.tagName === 'TEXTAREA' ||
                parent.tagName === 'INPUT' ||
                parent.isContentEditable) {
              return NodeFilter.FILTER_REJECT;
            }

            // 跳过已经高亮的节点及其子节点
            if (parent.classList.contains('keyword-highlight') ||
                parent.closest('.keyword-highlight')) {
              return NodeFilter.FILTER_REJECT;
            }

            // 跳过包含高亮标记的节点
            if (node.textContent.includes('keyword-highlight') ||
                node.textContent.includes('data-group=') ||
                node.textContent.includes('data-keyword=')) {
              return NodeFilter.FILTER_REJECT;
            }

            // 只处理包含文本的节点
            if (node.textContent.trim().length === 0) {
              return NodeFilter.FILTER_REJECT;
            }

            return NodeFilter.FILTER_ACCEPT;
          }
        }
    );

    const nodesToProcess = [];
    let node;
    while (node = walker.nextNode()) {
      nodesToProcess.push(node);
    }

    // 批量处理节点
    this.processNodes(nodesToProcess);
  }

  // 处理文本节点
  processNodes(nodes) {
    nodes.forEach(node => {
      this.highlightKeywordsInNode(node);
    });
  }

  // 在文本节点中高亮关键词
  highlightKeywordsInNode(textNode) {
    // 检查文本节点是否已经被处理过（在已经高亮的元素内部）
    if (textNode.parentElement && textNode.parentElement.classList.contains('keyword-highlight')) {
      return;
    }

    const originalText = textNode.textContent;
    let newHTML = originalText;
    let hasMatch = false;

    // 按关键词长度降序排序，避免短关键词在长关键词内部匹配
    const sortedKeywords = [...this.keywords].sort((a, b) => b.text.length - a.text.length);

    // 为每个关键词创建高亮
    sortedKeywords.forEach(keyword => {
      const group = this.groups.find(g => g.id === keyword.groupId);
      if (!group) return;

      const regex = this.settings.regexSupport ?
          new RegExp(keyword.text, 'gi') :
          new RegExp(this.escapeRegExp(keyword.text), 'gi');

      newHTML = newHTML.replace(regex, match => {
        // 检查匹配的文本是否已经在高亮标记内部
        const matchIndex = newHTML.indexOf(match);
        if (matchIndex > 0) {
          const beforeChar = newHTML[matchIndex - 1];
          const afterChar = newHTML[matchIndex + match.length];

          // 如果匹配的文本在引号内或标签属性内，跳过
          if (beforeChar === '"' || beforeChar === "'" || beforeChar === '=') {
            return match;
          }
        }

        hasMatch = true;

        // 转义HTML特殊字符，防止XSS
        const escapedGroupName = this.escapeHtml(group.name);
        const escapedTip = this.escapeHtml(keyword.tip);

        return `<mark class="keyword-highlight" 
                     data-group="${group.id}"
                     data-keyword="${keyword.id}"
                     data-group-name="${escapedGroupName}"
                     data-tip="${escapedTip}"
                     style="background-color: ${group.color}30; 
                            border-bottom: 1px dashed ${group.color};
                            padding: 0 1px;
                            margin: 0 1px;">${match}</mark>`;
      });
    });

    if (hasMatch && newHTML !== originalText) {
      const wrapper = document.createElement('span');
      wrapper.innerHTML = newHTML;

      // 保持按钮的默认光标
      const parent = textNode.parentElement;
      if (parent && (parent.tagName === 'BUTTON' || parent.closest('button'))) {
        wrapper.querySelectorAll('.keyword-highlight').forEach(hl => {
          hl.style.cursor = 'inherit';
        });
      }

      // 替换前检查父节点是否存在
      if (textNode.parentNode) {
        textNode.parentNode.replaceChild(wrapper, textNode);
        this.highlightedNodes.add(wrapper);
      }
    }
  }

  // 显示工具提示
  showTooltip(event, element) {
    if (!this.tooltip || this.isScrolling) return;

    const groupName = element.getAttribute('data-group-name');
    const tip = element.getAttribute('data-tip');

    // 更新工具提示内容
    this.tooltip.innerHTML = `
      <div style="font-weight: bold; margin-bottom: 2px;">${groupName}</div>
      <div style="color: ${this.settings.tooltipTheme === 'dark' ? '#ccc' : '#666'};">${tip || '暂无提示信息'}</div>
    `;

    // 保存当前高亮元素
    this.currentHighlight = element;

    // 更新工具提示位置
    this.positionTooltip(event);

    // 显示工具提示
    this.tooltip.style.opacity = '1';
  }

  // 定位工具提示
  positionTooltip(event) {
    if (!this.tooltip) return;

    const tooltipRect = this.tooltip.getBoundingClientRect();
    const mouseX = event.clientX;
    const mouseY = event.clientY;

    let top = mouseY + 15;
    let left = mouseX + 15;

    // 确保工具提示不会超出视口右侧
    if (left + tooltipRect.width > window.innerWidth - 10) {
      left = mouseX - tooltipRect.width - 15;
    }

    // 确保工具提示不会超出视口底部
    if (top + tooltipRect.height > window.innerHeight - 10) {
      top = mouseY - tooltipRect.height - 15;
    }

    // 确保工具提示不会超出视口顶部
    if (top < 10) {
      top = 10;
    }

    // 确保工具提示不会超出视口左侧
    if (left < 10) {
      left = 10;
    }

    // 应用位置
    this.tooltip.style.top = `${top}px`;
    this.tooltip.style.left = `${left}px`;
  }

  // 隐藏工具提示
  hideTooltip() {
    if (this.tooltip) {
      this.tooltip.style.opacity = '0';
      this.currentHighlight = null;
    }
  }

  // 转义正则表达式特殊字符
  escapeRegExp(string) {
    return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  }

  // 转义HTML特殊字符
  escapeHtml(unsafe) {
    if (!unsafe) return '';
    return unsafe
        .replace(/&/g, "&amp;")
        .replace(/</g, "&lt;")
        .replace(/>/g, "&gt;")
        .replace(/"/g, "&quot;")
        .replace(/'/g, "&#039;");
  }

  // 移除所有高亮
  removeHighlights() {
    this.highlightedNodes.forEach(node => {
      if (node.parentNode) {
        // 获取所有高亮元素的文本内容
        const highlights = node.querySelectorAll('.keyword-highlight');
        highlights.forEach(highlight => {
          const text = highlight.textContent;
          const textNode = document.createTextNode(text);
          highlight.parentNode.replaceChild(textNode, highlight);
        });

        // 如果包装器只剩下文本节点，则替换包装器
        if (node.children.length === 0 && node.textContent) {
          const textNode = document.createTextNode(node.textContent);
          node.parentNode.replaceChild(textNode, node);
        }
      }
    });
    this.highlightedNodes.clear();

    // 额外清理：查找并移除任何遗留的高亮标记
    const remainingHighlights = document.querySelectorAll('.keyword-highlight');
    remainingHighlights.forEach(highlight => {
      const text = highlight.textContent;
      const textNode = document.createTextNode(text);
      highlight.parentNode.replaceChild(textNode, highlight);
    });

    // 移除工具提示
    this.hideTooltip();
  }

  // 重新高亮
  rehighlight() {
    // 先完全移除所有高亮
    this.removeHighlights();

    // 短暂延迟确保DOM更新完成
    setTimeout(() => {
      this.startScan();
    }, 100);
  }
}

// 初始化高亮器
let highlighter;

// 当DOM加载完成后初始化
if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', () => {
    highlighter = new KeywordHighlighter();
  });
} else {
  highlighter = new KeywordHighlighter();
}